package com.adjy.pathbuilders.objects.button;

import android.view.MotionEvent;
import static com.adjy.pathbuilders.commons.Preconditions.check;
import com.adjy.pathbuilders.objects.button.listeners.ButtonListener;
import com.adjy.pathbuilders.rendering.GameCanvas;

public abstract class Button {
	
	protected float x, y;
	protected float width, height;
	private ButtonListener listener;
	protected boolean isSelected;
	
	public Button(float x, float y, float width, float height, ButtonListener listener) {
		check(width >= 0, "width must not be negative.");
		check(height >= 0, "height must not be negative.");
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
		this.listener = listener;
		isSelected = false;
	}
	
	public abstract void render(GameCanvas canvas, float timeElapsed);
	
	public void input(MotionEvent event) {
		
		switch (event.getActionMasked()) {
		case MotionEvent.ACTION_DOWN:
			if (pressed(event.getX(), event.getY())) {
				isSelected = true;
			} else {
				isSelected = false;
			}
			break;
		case MotionEvent.ACTION_MOVE:
			if (pressed(event.getX(), event.getY())) {
				isSelected = true;
			} else {
				isSelected = false;
			}
			break;
		case MotionEvent.ACTION_UP:
			if (pressed(event.getX(), event.getY())) {
				listener.onButtonPressed();
			}
			isSelected = false;
			break;
		default:
			break;
		}
	}
	
	private boolean pressed(float x, float y) {
		if (x > this.x && x < this.x + width) {
			// Is on X Range
			if (y > this.y && y < this.y + height) {
				// Is on Y Range
				return true;
			}
		}
		return false;
	}
	
}
